//
//  ZJFThiredViewController.m
//  OurTourism
//
//  Created by 张金峰 on 15/12/1.
//  Copyright © 2015年 Devil_Coming. All rights reserved.
//

#import "ZJFThiredViewController.h"
#import "MZNetHandle.h"
#import "ZJFThiredTableViewCell.h"
#import "Masonry.h"
#import "ZJFMapViewController.h"
#import "Entity.h"
#import "ZJFguiDeModel.h"
#import "CoreDataManager.h"
#import "UIImageView+WebCache.h"
@interface ZJFThiredViewController ()<UITableViewDataSource, UITableViewDelegate>
@property (nonatomic, strong)UITableView *tableView;
@property (nonatomic, strong)NSString *name;
@property (nonatomic, strong)NSString *yongHuMing;
@property (nonatomic, strong)NSString *riQi;
@property (nonatomic, strong)NSString *days;
@property (nonatomic, strong)NSString *picdomain;
@property (nonatomic, strong)NSString *coverpic;
@property (nonatomic, strong)NSString *imgTouXiang;
@property (nonatomic, strong)NSString *kmm;
@property (nonatomic, strong)NSString *likeCnt;
@property (nonatomic, strong)NSMutableArray *data;
@property (nonatomic, strong)NSNumber *tableY;
@property (nonatomic, strong)CoreDataManager *manager;
@property (nonatomic, strong)Entity *ent;
@property (nonatomic, strong)NSMutableArray *Map;
@end

@implementation ZJFThiredViewController
#pragma mark - 视图将要出现
- (void)viewWillAppear:(BOOL)animated
{
    self.tabBarController.tabBar.hidden = YES;
    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
    NSEntityDescription *entity = [NSEntityDescription entityForName:@"Entity" inManagedObjectContext:self.manager.managedObjectContext];//实体描述
    [fetchRequest setEntity:entity];//去*表查
    // Specify criteria for filtering which objects to fetch
    NSNumber *searchNumber = [NSNumber numberWithInteger:[self.listID integerValue]];
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"itemId = %@", searchNumber];
    [fetchRequest setPredicate:predicate];
    NSError *error = nil;
    NSArray *fetchedObjects = [self.manager.managedObjectContext executeFetchRequest:fetchRequest error:&error];
    if (fetchedObjects.count == 0) {
        self.ent = [NSEntityDescription insertNewObjectForEntityForName:@"Entity" inManagedObjectContext:self.manager.managedObjectContext];
        self.ent.pianYiLiang = @(0);
        self.ent.itemId = [NSNumber numberWithInteger:[self.listID integerValue]];
        [self.manager saveContext];
    }else{
        self.ent = fetchedObjects.firstObject;
        [self.tableView setContentOffset:CGPointMake(0, self.ent.pianYiLiang.floatValue)];
    }
    if (fetchedObjects == nil) {
        NSLog(@"失败");
    }
}

#pragma mark - 偏移方法
- (void)pianyi
{
    [self.tableView setContentOffset:CGPointMake(0, self.ent.pianYiLiang.floatValue)];
}
#pragma mark - 视图将要消失
- (void)viewWillDisappear:(BOOL)animated
{
    CGFloat pianyi = self.tableView.contentOffset.y;
    self.ent.pianYiLiang = [NSNumber numberWithFloat:pianyi];
    [self.manager saveContext];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor whiteColor];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]initWithImage:[[UIImage imageNamed:@"leftBack"]imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] style:UIBarButtonItemStylePlain target:self action:@selector(backToLast)];
    
    self.Map = [NSMutableArray array];
    self.manager = [CoreDataManager shareInstance];//单例初始化
    NSLog(@"%@",[self.manager applicationDocumentsDirectory]);
    
    //[self core];
    [self loadMBProgress];
    [self getData];
    
}
#pragma mark - 请求数据
- (void)getData
{
    NSString *url = [NSString stringWithFormat:@"http://app6.117go.com/demo27/php/formAction.php?recType=0&id1=508277&id2=1&submit=getATour2&tourid=%@&v=i6.4.2&vc=AppStore&vd=b3c1b4cf8b498fb8&lang=zh-Hans&verify=70b2429e21d1a72d46a3d799872525fd", self.listID];
    
    [MZNetHandle getUrl:url cookie:nil result:^(id result) {
        self.name = result[@"obj"][@"title"];
        self.yongHuMing = result[@"obj"][@"owner"][@"nickname"];
        self.riQi = result[@"obj"][@"startdate"];
        self.days = result[@"obj"][@"days"];
        self.coverpic = result[@"obj"][@"owner"][@"coverpic"];
        self.picdomain = result[@"obj"][@"picdomain"];
        self.imgTouXiang = [NSString stringWithFormat:@"%@%@%@",self.picdomain, @"upload/", self.coverpic];
        self.Map = result[@"obj"][@"PathMap"];
        self.kmm = result[@"obj"][@"owner"][@"tourCnt"];
        self.likeCnt = result[@"obj"][@"likeCnt"];
        NSArray *arr = [NSArray array];
        self.data = [NSMutableArray array];
        arr = result[@"obj"][@"records"];
        self.data = [ZJFguiDeModel transformWithArray:arr];
        
        [self.hud removeFromSuperview];
        [self createTableView];
        [self pianyi];
        //        [self.tableView reloadData];
    }];
    
}
#pragma mark - 创建tableView
- (void)createTableView
{
    self.tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width, self.view.bounds.size.height) style:UITableViewStylePlain];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    [self.view addSubview:self.tableView];
    
}

#pragma mark - 按钮触发方法
- (void)backToLast
{
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark - 头部
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    UIView *titleview = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 0)];//最底层
    
    titleview.backgroundColor = [UIColor colorWithRed:250 / 255. green:246 / 255. blue:232 / 255. alpha:1];
    UIImageView *ditu = [[UIImageView alloc]init];//地图
    [titleview addSubview:ditu];
    ditu.image = [UIImage imageNamed:@"ditu.jpg"];
    [ditu mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(titleview.mas_top).offset(0);
        make.left.mas_equalTo(titleview.mas_left).offset(0);
        make.size.mas_equalTo(CGSizeMake(self.view.frame.size.width, 180));
    }];
    ditu.backgroundColor = [UIColor orangeColor];
    
    UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
    btn.frame = CGRectMake(100, 20, 20, 20);
    btn.imageView.image = [UIImage imageNamed:@""];
    btn.backgroundColor = [UIColor redColor];
    [ditu addSubview:btn];
    [btn addTarget:self action:@selector(BtnAction) forControlEvents:UIControlEventTouchUpInside];
    
    UILabel *lable = [[UILabel alloc] init];//头像外层
    [titleview addSubview:lable];
    lable.backgroundColor = [UIColor colorWithRed:250 / 255. green:246 / 255. blue:232 / 255. alpha:1];
    [lable mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(ditu.mas_top).offset(140);
        make.left.mas_equalTo(ditu.mas_left).offset((self.view.frame.size.width / 2) - 35);
        make.size.mas_equalTo(CGSizeMake(80, 80));
    }];
    lable.layer.cornerRadius = 40;
    lable.layer.masksToBounds = YES;
    UIImageView *touXiang = [[UIImageView alloc] init];//头像
    [lable addSubview:touXiang];
    // NSLog(@"qqqqqqqqqqq  %@",self.imgTouXiang);
    [touXiang sd_setImageWithURL:[NSURL URLWithString:self.imgTouXiang] placeholderImage:nil];
    [touXiang mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(lable.mas_top).offset(5);
        make.left.mas_equalTo(lable.mas_left).offset(5);
        make.size.mas_equalTo(CGSizeMake(70, 70));
    }];
    touXiang.backgroundColor = [UIColor yellowColor];
    touXiang.layer.cornerRadius = 35;
    touXiang.layer.masksToBounds = YES;
    
    UILabel *by = [[UILabel alloc] init];//by
    [titleview addSubview:by];
    [by mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(touXiang.mas_bottom).offset(10);
        make.left.mas_equalTo(touXiang.mas_left).offset(-25);
        make.size.mas_equalTo(CGSizeMake(30, 20));
    }];
    by.text = @"By";
    
    UILabel *yongHuMing = [[UILabel alloc] init];//用户名
    [titleview addSubview:yongHuMing];
    yongHuMing.text = self.yongHuMing;
    // yongHuMing.backgroundColor = [UIColor blueColor];
    [yongHuMing mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(by.mas_bottom).offset(-16);
        make.left.mas_equalTo(by.mas_right).offset(3);
        make.size.mas_equalTo(CGSizeMake(150, 15));
    }];
    
    UILabel *name = [[UILabel alloc] init]; //名字
    [titleview addSubview:name];
    name.text = self.name;
    name.numberOfLines = 2;
    name.font = [UIFont boldSystemFontOfSize:22];
    name.textColor = [UIColor blackColor];
    name.textAlignment = NSTextAlignmentCenter;
    //  name.backgroundColor = [UIColor whiteColor];
    [name mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(yongHuMing.mas_bottom).offset(20);
        make.centerX.mas_equalTo(titleview.mas_centerX);
        make.left.mas_equalTo(titleview.mas_left).offset(30);
        make.right.mas_equalTo(titleview.mas_right).offset(-30);
        make.size.mas_equalTo(CGSizeMake(0, 60));
    }];
    
    UILabel *hengXian = [[UILabel alloc] init];//1像素横线
    [titleview addSubview:hengXian];
    hengXian.backgroundColor = [UIColor grayColor];
    [hengXian mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(name.mas_bottom).offset(20);
        make.left.mas_equalTo(titleview.mas_left).offset(40);
        make.size.mas_equalTo(CGSizeMake(self.view.frame.size.width - 80, 1));
    }];
    UILabel *shuXian = [[UILabel alloc] init];//左分割线
    [titleview addSubview:shuXian];
    shuXian.backgroundColor = [UIColor grayColor];
    [shuXian mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(hengXian.mas_top).offset(15);
        make.left.mas_equalTo(titleview.mas_left).offset(self.view.frame.size.width / 3 + 15);
        make.size.mas_equalTo(CGSizeMake(1, 50));
    }];
    
    UILabel *riQi = [[UILabel alloc] init];//日期
    [titleview addSubview:riQi];
    // riQi.backgroundColor = [UIColor greenColor];
    riQi.text = self.riQi;
    riQi.font = [UIFont boldSystemFontOfSize:13];
    riQi.textColor = [UIColor blackColor];
    [riQi mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(hengXian.mas_top).offset(10);
        make.left.mas_equalTo(hengXian.mas_left).offset(10);
        make.right.mas_equalTo(shuXian.mas_left).offset(-10);
        make.size.mas_equalTo(CGSizeMake(0, 15));
    }];
    
    UILabel *tian = [[UILabel alloc] init];
    [titleview addSubview:tian];
    // tian.text = self.days;
    tian.textAlignment = NSTextAlignmentCenter;
    tian.text = [NSString stringWithFormat:@"%@%@",self.days,@"天"];
    tian.textColor = [UIColor grayColor];
    // tian.backgroundColor = [UIColor yellowColor];
    [tian mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(riQi.mas_bottom).offset(15);
        make.left.mas_equalTo(riQi.mas_left).offset(10);
        make.right.mas_equalTo(riQi.mas_right).offset(-10);
        make.size.mas_equalTo(CGSizeMake(0, 15));
    }];
    
    UILabel *licheng = [[UILabel alloc] init];//里程
    [titleview addSubview:licheng];
    // licheng.backgroundColor = [UIColor grayColor];
    licheng.text = @"里程";
    licheng.font = [UIFont boldSystemFontOfSize:15];
    [licheng mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(hengXian.mas_top).offset(10);
        //make.left.mas_equalTo(shuXian.mas_left).offset(35);
        make.centerX.mas_equalTo(hengXian.mas_centerX);
        make.size.mas_equalTo(CGSizeMake(40, 15));
    }];
    
    UILabel *km = [[UILabel alloc] init];//**km
    [titleview addSubview:km];
    //km.backgroundColor = [UIColor blueColor];
    km.textColor = [UIColor grayColor];
    km.textAlignment = NSTextAlignmentCenter;
    km.text = [NSString stringWithFormat:@"%@%@",self.kmm, @"KM"];
    [km mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(licheng.mas_bottom).offset(15);
        make.centerX.mas_equalTo(licheng.mas_centerX);
        make.size.mas_equalTo(CGSizeMake(80, 15));
    }];
    UILabel *youShuXian = [[UILabel alloc] init];//右数线
    [titleview addSubview:youShuXian];
    youShuXian.backgroundColor = [UIColor grayColor];
    [youShuXian mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(hengXian.mas_top).offset(15);
        make.right.mas_equalTo(titleview.mas_right).offset( -(self.view.frame.size.width /3 + 15));
        make.size.mas_equalTo(CGSizeMake(1, 50));
    }];
    
    UILabel *like = [[UILabel alloc] init];
    [titleview addSubview:like];
    // like.backgroundColor = [UIColor yellowColor];
    like.text = @"喜欢";
    like.font = [UIFont boldSystemFontOfSize:15];
    [like mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(hengXian.mas_top).offset(10);
        make.right.mas_equalTo(hengXian.mas_right).offset(-25);
        make.size.mas_equalTo(CGSizeMake(40, 15));
    }];
    
    UILabel *likeCount = [[UILabel alloc] init];
    [titleview addSubview:likeCount];
    likeCount.text = self.likeCnt;
    likeCount.textColor = [UIColor grayColor];
    //  likeCount.backgroundColor = [UIColor purpleColor];
    [likeCount mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(like.mas_bottom).offset(15);
        make.right.mas_equalTo(like);
        make.size.mas_equalTo(CGSizeMake(40, 15));
    }];
    self.tableView.tableHeaderView = titleview;
    return titleview;
}
#pragma mark - button 点击方法
- (void)BtnAction
{
    ZJFMapViewController *map = [[ZJFMapViewController alloc] init];
    map.returnMap = self.Map;
    [self.navigationController pushViewController:map animated:YES];
}
#pragma mark - tableview协议方法
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    
    ZJFThiredTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
    if (!cell) {
        cell = [[ZJFThiredTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cell"];
    }
    [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
    cell.backgroundColor = [UIColor colorWithRed:0.98 green:0.97 blue:0.93 alpha:1];
    //  cell.modelRecords = self.modelRecordsArr[indexPath.row];
    cell.Model = self.data[indexPath.row];
    return cell;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.data.count;
}

#pragma mark -  行高
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    ZJFguiDeModel *model = self.data[indexPath.row];
    CGFloat h = [[self class] heightWithText:model.words fontSize:17 Width:[UIScreen mainScreen].bounds.size.width - 40];
    
    
    return 255 + 5 + h + 2 + 40 + 15;
}
#pragma mark - 头部高度
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 410;
}


#pragma mark - 计算文本高度的方法
+ (CGFloat)heightWithText:(NSString *)text fontSize:(CGFloat)fontsize Width:(CGFloat)width

{
    //设置一个字典 保存文本属性
    NSDictionary *dic = @{NSFontAttributeName:[UIFont systemFontOfSize:fontsize]};
    
    //预设尺寸 文本最大不会超过这个范围
    CGSize size = CGSizeMake(width, 2000);
    //根据文本信息 计算得到一个CGRect
    //参数1. 尺寸范围
    //参数2. 获取文本尺寸的方式
    //参数3. 文本属性
    //参数4. 无用信息(上下文)
    CGRect rect = [text boundingRectWithSize:size options:NSStringDrawingUsesLineFragmentOrigin attributes:dic context:nil];
    return rect.size.height;
}




//#pragma mark-滑动手势1
//- (void)addScreenEdgePan
//{
//    UIScreenEdgePanGestureRecognizer *screenEdgePan = [[UIScreenEdgePanGestureRecognizer alloc] initWithTarget:self action:@selector(presentLeftMenuViewController:)];
//    screenEdgePan.edges = UIRectEdgeLeft;
//    [self.view addGestureRecognizer:screenEdgePan];
//    [self.tableView addGestureRecognizer:screenEdgePan];
//    [screenEdgePan release];
//}
//#pragma mark-滑动手势2
//-(void)presentLeftMenuViewController:(UIScreenEdgePanGestureRecognizer *)edge
//{
//    [self.navigationController popViewControllerAnimated:YES];
//}

- (void)loadMBProgress
{
    self.hud = [[MBProgressHUD alloc] initWithView:self.view];
    
    self.hud.dimBackground = NO;
    //设置对话框文字
    self.hud.labelText = @"loading";
    self.hud.minShowTime = 50;
    self.hud.activityIndicatorColor = [UIColor whiteColor];
    self.hud.labelColor = [UIColor whiteColor];
    
    [self.view addSubview:self.hud];
    [self.hud showAnimated:YES whileExecutingBlock:^{
        //对话框显示时需要执行的操作
        sleep(1);
    } completionBlock:^{
        //操作执行完后取消对话框
        [self.hud removeFromSuperview];
        self.hud = nil;
    }];
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
